package com.hibase.upms.service.organization.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hibase.common.exception.HibaseException;
import com.hibase.core.mybatis.entity.BaseDO;
import com.hibase.core.mybatis.service.BaseServiceImpl;
import com.hibase.core.web.entity.OperationIdEntity;
import com.hibase.upms.constant.MenuManagerConstant;
import com.hibase.upms.constant.OrgManagerConstant;
import com.hibase.upms.entity.organization.MdsOrganization;
import com.hibase.upms.entity.organization.vo.MdsOrgSearchVO;
import com.hibase.upms.entity.userorg.MdsOrgUser;
import com.hibase.upms.mapper.organization.MdsOrganizationMapper;
import com.hibase.upms.service.organization.IMdsOrganizationService;
import com.hibase.upms.service.userorg.IMdsOrgUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ChrisCui
 * @since 2019-04-17
 */
@Service
@Log4j2
public class MdsOrganizationServiceImpl extends BaseServiceImpl<MdsOrganizationMapper, MdsOrganization> implements IMdsOrganizationService {

    @Autowired
    private IMdsOrgUserService mdsOrgUserService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeUser(MdsOrganization mdsOrg) {
        if (StrUtil.isBlank(mdsOrg.getId())) {
            mdsOrg.setStatus(OrgManagerConstant.RECORD_STATUS_ENABLE);
            mdsOrg.setChildNumber(0);
        }

        // 查询到旧的记录
        MdsOrganization old = null;

        if (StrUtil.isNotBlank(mdsOrg.getId())) {

            old = super.getById(mdsOrg.getId());
        }

        if (StrUtil.isBlank(mdsOrg.getParentId())) {

            mdsOrg.setParentId(null);
        }

        super.store(mdsOrg);

        // 刷新父级id
        this.settingsFullIds(old,mdsOrg);
    }

    /**
     * 设置全路径
     */
    private void settingsFullIds(MdsOrganization old,MdsOrganization mdsOrganization) {

        if (old != null && StrUtil.isNotBlank(mdsOrganization.getParentId()) && mdsOrganization.getParentId().equals(old.getParentId())) {

            return;
        }

        MdsOrganization parent = null;

        // 最顶级目录
        if (StrUtil.isNotBlank(mdsOrganization.getParentId())) {

            // 根据父节点查询数据
            parent = super.getById(mdsOrganization.getParentId(), true);
        }

        StringBuilder allParentIds = new StringBuilder();
        StringBuilder fullName = new StringBuilder();

        BigDecimal level = BigDecimal.ZERO;

        if (parent != null) {

            allParentIds.append(parent.getParentIds());
            allParentIds.append(MenuManagerConstant.CONTENT_SPLIT);

            fullName.append(parent.getFullName());
            fullName.append(MenuManagerConstant.CONTENT_SPLIT_SPACE);

            //level = parent.getLevel();

            // 当前选择的上一层级节点数加1
            parent.setChildNumber(parent.getChildNumber() + 1);

            super.store(parent);
        }

        allParentIds.append(mdsOrganization.getId());
        mdsOrganization.setParentIds(allParentIds.toString());

        fullName.append(mdsOrganization.getName());
        mdsOrganization.setFullName(fullName.toString());

        // 设置层级结构
        // mdsOrganization.setLevel(level.add(BigDecimal.ONE));

        super.store(mdsOrganization);

        if (old != null && StrUtil.isNotBlank(old.getParentId())) {

            MdsOrganization oldParent = this.getById(old.getParentId());

            // 旧的父记录减1
            oldParent.setChildNumber(oldParent.getChildNumber() - 1);
            super.store(oldParent);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class,readOnly = false)
    public void changeOrgStatus(List<String> ids, boolean recordStatus) {

        List<MdsOrganization> updateList = new ArrayList<>();
        List<MdsOrganization> listByIds = super.listByIds(ids);
        for (MdsOrganization selectOrg : listByIds){
//            MdsOrganization selectOrg = super.getById(id);
            if (selectOrg.getStatus()==recordStatus){
                throw new HibaseException(selectOrg.getId()  + "禁止操作");
            }
            MdsOrganization org = new MdsOrganization();
            org.setId(selectOrg.getId());
            org.setStatus(recordStatus);
            updateList.add(org);
            
            //查询是否有子组织，有修改
//            List<MdsOrganization> selectBatchIds = baseMapper.selectList(Wrappers.<MdsOrganization>lambdaQuery()
//            		.like(MdsOrganization :: getParentIds, selectOrg.getParentIds()));
//            if (CollUtil.isNotEmpty(selectBatchIds)) {
//            	Set<String> parentIdsSet = selectBatchIds.stream().map( e -> e.getParentIds()).collect(Collectors.toSet());
//            	if (parentIdsSet.contains(ids)) {
//					continue;
//				}else {
//					
//				}
//			}
        }
       
        
        if (CollUtil.isNotEmpty(updateList)){
            super.updateBatchById(updateList);
        }
    }

    @Override
    public PageInfo<MdsOrganization> selectList(MdsOrgSearchVO searchVO) {

        QueryWrapper<MdsOrganization> queryWrapper = new QueryWrapper<>();

        if (StrUtil.isNotBlank(searchVO.getCode())) {

            queryWrapper.like("code", searchVO.getCode());
        }
        if (StrUtil.isNotBlank(searchVO.getName())) {

            queryWrapper.like("name", searchVO.getName());
        }
        if (StrUtil.isNotBlank(searchVO.getBizType())) {

            queryWrapper.eq("biz_type", searchVO.getBizType());
        }
        if (StrUtil.isNotBlank(searchVO.getParentId())) {

            queryWrapper.eq("parent_id", searchVO.getParentId());
        }
        if (StrUtil.isNotBlank(searchVO.getKeyWord())){
            queryWrapper.like("code", searchVO.getKeyWord()).or().like("name",searchVO.getKeyWord());
        }

        PageInfo<MdsOrganization> result = super.page(searchVO, queryWrapper);

        return result;
    }

    @Override
    public void updateFullIds(String id) {

        super.baseMapper.updateFullIds(id);
    }

    @Override
    public void refreshChildNumber() {
        super.baseMapper.refreshChildNumber();
    }

    @Override
    public List<MdsOrganization> selectChildList(String id) {
        List<MdsOrganization> result = new ArrayList<>();

        List<MdsOrganization> allOrg = super.list();

        return result;
    }

    /**
     * 查询组织树层级
     * @param  id  当前父节点
     * @param list  源节点
     * @return
     */
    @Override
    public List<MdsOrganization> recursionOrg(String id, List<MdsOrganization> list){
        // step01 构建子菜单
        List<MdsOrganization> childList = new ArrayList<>();

        // step02 关联子节点和父节点
        list.forEach(org ->{
            if(StrUtil.equals(org.getParentId(),id)){
                childList.add(org);
            }
        });

        // step03 递归子节点
        childList.forEach(org ->{
            org.setChildList(recursionOrg(org.getId(),list));
        });

        // step04 递归出口
        if(CollUtil.isEmpty(childList)){
            return ListUtil.toList();
        }
        return childList;
    }

    /**
     * 查询组织树非层级
     * @param id
     * @param list
     * @param result
     * @return
     */
    @Override
    public List<MdsOrganization> recursionOrg(String id, List<MdsOrganization> list,List<MdsOrganization> result){
        // step01 构建子菜单
        List<MdsOrganization> childList = new ArrayList<>();

        // step02 关联子节点和父节点
        list.forEach(org ->{
            if(StrUtil.equals(org.getParentId(),id)){
                childList.add(org);
                result.add(org);
            }
        });

        // step03 递归子节点
        childList.forEach(org ->{
            result.addAll(recursionOrg(org.getId(),list));
        });

        // step04 递归出口
        if(CollUtil.isEmpty(childList)){
            return ListUtil.toList();
        }
        return result;
    }

    @Override
    public PageInfo selectChildOrg(OperationIdEntity idEntity) {
        //得到当前用户的组织
        MdsOrgUser orgUser = mdsOrgUserService.getOne(Wrappers.<MdsOrgUser>lambdaQuery()
                .eq(MdsOrgUser::getUserId, idEntity.getId())
        );
        List<MdsOrganization> list = super.list();
        List<MdsOrganization> result = ListUtil.toList();
        List<MdsOrganization> childOrg = this.recursionOrg(orgUser.getOrgId(), list, result);
        if(CollUtil.isNotEmpty(childOrg)){
            return super.page(idEntity,Wrappers.<MdsOrganization>query()
                .in("id",childOrg.stream().map(BaseDO::getId).collect(Collectors.toList()))
            );
        }
        return new PageInfo(PageHelper.startPage(idEntity.getCurrentPage(),idEntity.getPageSize()));
    }
}
